Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,          // 加载状态
    mistakes: [],           // 错题列表
    currentIndex: 0,        // 当前题目索引
    currentQuestion: null,  // 当前题目
    options: {},            // 当前题目选项
    selectedOption: '',     // 选中的选项
    answered: false,        // 是否已作答
    isCorrect: false,       // 是否正确
    isLastQuestion: false,  // 是否最后一题
    totalQuestions: 0,      // 总题目数
    completed: false,       // 是否完成练习
    correctCount: 0,        // 正确数量
    wrongCount: 0,          // 错误数量
    correctRate: 0          // 正确率
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadPracticeMistakes();
  },

  /**
   * 加载练习错题
   */
  loadPracticeMistakes() {
    // 从本地存储获取错题
    const mistakes = wx.getStorageSync('practice_mistakes');
    console.log('从缓存获取的错题:', mistakes);
    
    if (!mistakes || mistakes.length === 0) {
      this.setData({
        loading: false
      });
      return;
    }
    
    // 随机排序错题
    const shuffledMistakes = this.shuffleArray([...mistakes]);
    
    this.setData({
      mistakes: shuffledMistakes,
      totalQuestions: shuffledMistakes.length,
      loading: false
    }, () => {
      this.showQuestion(0);
    });
  },
  
  /**
   * 显示指定索引的题目
   */
  showQuestion(index) {
    console.log('显示题目，索引:', index);
    const { mistakes } = this.data;
    console.log('错题列表长度:', mistakes.length);
    
    if (index >= mistakes.length) {
      console.log('索引超出范围，调用finishPractice()');
      this.finishPractice();
      return;
    }
    
    const currentQuestion = mistakes[index];
    console.log('当前题目:', currentQuestion);
    let options = {};
    
    try {
      // 解析选项
      if (currentQuestion.options) {
        try {
          options = JSON.parse(currentQuestion.options);
        } catch (error) {
          console.error('选项解析失败，尝试其他解析方式', error);
          // 尝试直接使用选项（可能已经是对象）
          if (typeof currentQuestion.options === 'object') {
            options = currentQuestion.options;
          }
        }
      }
    } catch (error) {
      console.error('解析选项失败:', error);
    }
    
    this.setData({
      currentIndex: index,
      currentQuestion,
      options,
      selectedOption: '',
      answered: false,
      isCorrect: false,
      isLastQuestion: index === mistakes.length - 1
    }, () => {
      console.log('showQuestion更新后的状态:', {
        currentIndex: this.data.currentIndex,
        totalQuestions: this.data.totalQuestions,
        isLastQuestion: this.data.isLastQuestion
      });
    });
  },
  
  /**
   * 选择选项
   */
  onOptionSelect(e) {
    this.setData({
      selectedOption: e.detail
    });
  },
  
  /**
   * 提交答案
   */
  submitAnswer() {
    console.log('点击了提交答案按钮');
    const { currentQuestion, selectedOption } = this.data;
    console.log('当前题目:', currentQuestion);
    console.log('选中的选项:', selectedOption);
    
    const isCorrect = selectedOption === currentQuestion.correctAnswer;
    console.log('答案是否正确:', isCorrect);
    console.log('当前是否最后一题:', this.data.isLastQuestion);
    
    this.setData({
      answered: true,
      isCorrect
    });
    
    // 统计正确/错误数量
    if (isCorrect) {
      this.setData({
        correctCount: this.data.correctCount + 1
      });
    } else {
      this.setData({
        wrongCount: this.data.wrongCount + 1
      });
    }
  },
  
  /**
   * 下一题
   */
  nextQuestion() {
    console.log('点击了下一题按钮');
    console.log('当前题目索引:', this.data.currentIndex);
    console.log('总题目数:', this.data.totalQuestions);
    console.log('是否最后一题:', this.data.isLastQuestion);
    
    const nextIndex = this.data.currentIndex + 1;
    console.log('下一题索引:', nextIndex);
    
    this.showQuestion(nextIndex);
  },
  
  /**
   * 完成练习
   */
  finishPractice() {
    console.log('点击了完成练习按钮');
    const { correctCount, totalQuestions } = this.data;
    console.log('练习统计：', { correctCount, totalQuestions });
    const correctRate = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
    console.log('计算的正确率：', correctRate);
    
    this.setData({
      currentQuestion: null,
      completed: true,
      correctRate
    }, () => {
      console.log('completed状态已设置为true');
      console.log('当前页面数据：', this.data);
      
      // 显示提示
      wx.showToast({
        title: '练习已完成',
        icon: 'success',
        duration: 2000
      });
    });
  },
  
  /**
   * 返回错题列表
   */
  backToList() {
    wx.navigateBack();
  },
  
  /**
   * 重新练习
   */
  restartPractice() {
    this.setData({
      currentIndex: 0,
      currentQuestion: null,
      options: {},
      selectedOption: '',
      answered: false,
      isCorrect: false,
      isLastQuestion: false,
      completed: false,
      correctCount: 0,
      wrongCount: 0,
      correctRate: 0
    }, () => {
      this.loadPracticeMistakes();
    });
  },
  
  /**
   * 数组随机排序
   */
  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }
}) 